# coding: utf-8
from typing import Union

from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QLabel, QWidget, QAbstractButton, QHBoxLayout, QStackedWidget
from qfluentwidgets import FluentIconBase, NavigationItemPosition
from qfluentwidgets.window.fluent_window import TitleBar
from qframelesswindow import FramelessWindow

from common import StyleSheet
from .navigation_bar import CustomNavigationBar


class StandardTitleBar(TitleBar):
    """ Title bar with icon and title """

    def __init__(self, parent):
        super().__init__(parent)
        # add window icon
        self.iconLabel = QLabel(self)
        self.iconLabel.setFixedSize(20, 20)
        self.hBoxLayout.insertSpacing(0, 10)
        self.hBoxLayout.insertWidget(1, self.iconLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.window().windowIconChanged.connect(self.setIcon)

        # add title label
        self.titleLabel = QLabel(self)
        self.titleLabel.setObjectName("titleLabel")
        self.hBoxLayout.insertWidget(2, self.titleLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.window().windowTitleChanged.connect(self.setTitle)

    def setTitle(self, title):
        """ set the title of title bar
        Parameters
        ----------
        title: str
            the title of title bar
        """
        self.titleLabel.setText(title)
        self.titleLabel.adjustSize()

    def setIcon(self, icon):
        """ set the icon of title bar
        Parameters
        ----------
        icon: QIcon | QPixmap | str
            the icon of title bar
        """
        self.iconLabel.setPixmap(QIcon(icon).pixmap(20, 20))


class CustomWindow(FramelessWindow):
    clicked = Signal(QAbstractButton)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.hBoxLayout = QHBoxLayout(self)
        self.navigationInterface = CustomNavigationBar(self)
        self.stackedWidget = QStackedWidget(self)

        self.__initWidget()

    def __initWidget(self):
        self.setTitleBar(StandardTitleBar(self))
        self.titleBar.setFixedHeight(30)
        self.setMinimumSize(800, 600)
        self.navigationInterface.setFixedWidth(220)
        StyleSheet.TitleBar.apply(self)

        self.navigationInterface.buttonGroup.buttonClicked.connect(self.clicked)

        self.hBoxLayout.setContentsMargins(0, 30, 0, 0)
        self.hBoxLayout.addWidget(self.navigationInterface)
        self.hBoxLayout.addWidget(self.stackedWidget, 1)

    def addSubInterface(self, interface: QWidget, icon: Union[FluentIconBase, QIcon, str], text: str,
                        position=NavigationItemPosition.TOP):
        self.navigationInterface.addItem(icon, text, position)
        self.stackedWidget.addWidget(interface)
